const express = require('express');
const router = express.Router();
const { Role, Permission, User } = require('../models');
const auth = require('../middleware/auth');
const adminAuth = require('../middleware/adminAuth');

// 获取所有权限列表
router.get('/permissions', auth, adminAuth, async (req, res) => {
  try {
    const permissions = await Permission.find()
      .sort({ module: 1, action: 1 });
    
    // 按模块分组
    const groupedPermissions = permissions.reduce((acc, permission) => {
      if (!acc[permission.module]) {
        acc[permission.module] = [];
      }
      acc[permission.module].push(permission);
      return acc;
    }, {});
    
    res.json({
      success: true,
      data: {
        permissions,
        groupedPermissions
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取权限列表失败',
      error: error.message
    });
  }
});

// 创建权限
router.post('/permissions', auth, adminAuth, async (req, res) => {
  try {
    const { name, displayName, description, module, action, resource } = req.body;
    
    const permission = new Permission({
      name,
      displayName,
      description,
      module,
      action,
      resource
    });
    
    await permission.save();
    
    res.status(201).json({
      success: true,
      message: '权限创建成功',
      data: permission
    });
  } catch (error) {
    if (error.code === 11000) {
      res.status(400).json({
        success: false,
        message: '权限名称已存在'
      });
    } else {
      res.status(400).json({
        success: false,
        message: '创建权限失败',
        error: error.message
      });
    }
  }
});

// 更新权限
router.put('/permissions/:id', auth, adminAuth, async (req, res) => {
  try {
    const { displayName, description, module, action, resource } = req.body;
    
    const permission = await Permission.findByIdAndUpdate(
      req.params.id,
      { displayName, description, module, action, resource },
      { new: true, runValidators: true }
    );
    
    if (!permission) {
      return res.status(404).json({
        success: false,
        message: '权限不存在'
      });
    }
    
    res.json({
      success: true,
      message: '权限更新成功',
      data: permission
    });
  } catch (error) {
    res.status(400).json({
      success: false,
      message: '更新权限失败',
      error: error.message
    });
  }
});

// 删除权限
router.delete('/permissions/:id', auth, adminAuth, async (req, res) => {
  try {
    const permission = await Permission.findByIdAndDelete(req.params.id);
    
    if (!permission) {
      return res.status(404).json({
        success: false,
        message: '权限不存在'
      });
    }
    
    // 从所有角色中移除该权限
    await Role.updateMany(
      { permissions: permission.name },
      { $pull: { permissions: permission.name } }
    );
    
    res.json({
      success: true,
      message: '权限删除成功'
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '删除权限失败',
      error: error.message
    });
  }
});

// 获取所有角色列表
router.get('/roles', auth, adminAuth, async (req, res) => {
  try {
    const { page = 1, limit = 20, search, status } = req.query;
    
    const query = {};
    
    if (search) {
      query.$or = [
        { name: { $regex: search, $options: 'i' } },
        { displayName: { $regex: search, $options: 'i' } }
      ];
    }
    
    if (status !== undefined) {
      query.status = parseInt(status);
    }
    
    const roles = await Role.find(query)
      .sort({ createdAt: -1 })
      .limit(limit * 1)
      .skip((page - 1) * limit);
    
    const total = await Role.countDocuments(query);
    
    // 获取每个角色的用户数量
    const rolesWithUserCount = await Promise.all(
      roles.map(async (role) => {
        const userCount = await User.countDocuments({ role: role.name });
        return {
          ...role.toObject(),
          userCount
        };
      })
    );
    
    res.json({
      success: true,
      data: {
        roles: rolesWithUserCount,
        pagination: {
          current: parseInt(page),
          total: Math.ceil(total / limit),
          pageSize: parseInt(limit),
          totalItems: total
        }
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取角色列表失败',
      error: error.message
    });
  }
});

// 获取角色详情
router.get('/roles/:id', auth, adminAuth, async (req, res) => {
  try {
    const role = await Role.findById(req.params.id);
    
    if (!role) {
      return res.status(404).json({
        success: false,
        message: '角色不存在'
      });
    }
    
    // 获取权限详情
    const permissions = await Permission.find({
      name: { $in: role.permissions }
    });
    
    // 获取使用该角色的用户
    const users = await User.find({ role: role.name })
      .select('username phone email status')
      .limit(10);
    
    const userCount = await User.countDocuments({ role: role.name });
    
    res.json({
      success: true,
      data: {
        role,
        permissions,
        users,
        userCount
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取角色详情失败',
      error: error.message
    });
  }
});

// 创建角色
router.post('/roles', auth, adminAuth, async (req, res) => {
  try {
    const { name, displayName, description, permissions } = req.body;
    
    // 验证权限是否存在
    const validPermissions = await Permission.find({
      name: { $in: permissions }
    });
    
    if (validPermissions.length !== permissions.length) {
      return res.status(400).json({
        success: false,
        message: '包含无效的权限'
      });
    }
    
    const role = new Role({
      name,
      displayName,
      description,
      permissions
    });
    
    await role.save();
    
    res.status(201).json({
      success: true,
      message: '角色创建成功',
      data: role
    });
  } catch (error) {
    if (error.code === 11000) {
      res.status(400).json({
        success: false,
        message: '角色名称已存在'
      });
    } else {
      res.status(400).json({
        success: false,
        message: '创建角色失败',
        error: error.message
      });
    }
  }
});

// 更新角色
router.put('/roles/:id', auth, adminAuth, async (req, res) => {
  try {
    const { displayName, description, permissions, status } = req.body;
    
    const role = await Role.findById(req.params.id);
    
    if (!role) {
      return res.status(404).json({
        success: false,
        message: '角色不存在'
      });
    }
    
    if (role.isSystem && status === 0) {
      return res.status(400).json({
        success: false,
        message: '系统角色不能禁用'
      });
    }
    
    // 验证权限是否存在
    if (permissions) {
      const validPermissions = await Permission.find({
        name: { $in: permissions }
      });
      
      if (validPermissions.length !== permissions.length) {
        return res.status(400).json({
          success: false,
          message: '包含无效的权限'
        });
      }
    }
    
    const updatedRole = await Role.findByIdAndUpdate(
      req.params.id,
      { displayName, description, permissions, status },
      { new: true, runValidators: true }
    );
    
    res.json({
      success: true,
      message: '角色更新成功',
      data: updatedRole
    });
  } catch (error) {
    res.status(400).json({
      success: false,
      message: '更新角色失败',
      error: error.message
    });
  }
});

// 删除角色
router.delete('/roles/:id', auth, adminAuth, async (req, res) => {
  try {
    const role = await Role.findById(req.params.id);
    
    if (!role) {
      return res.status(404).json({
        success: false,
        message: '角色不存在'
      });
    }
    
    if (role.isSystem) {
      return res.status(400).json({
        success: false,
        message: '系统角色不能删除'
      });
    }
    
    // 检查是否有用户使用该角色
    const userCount = await User.countDocuments({ role: role.name });
    if (userCount > 0) {
      return res.status(400).json({
        success: false,
        message: `该角色正在被 ${userCount} 个用户使用，无法删除`
      });
    }
    
    await Role.findByIdAndDelete(req.params.id);
    
    res.json({
      success: true,
      message: '角色删除成功'
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '删除角色失败',
      error: error.message
    });
  }
});

// 分配角色给用户
router.post('/users/:userId/assign-role', auth, adminAuth, async (req, res) => {
  try {
    const { roleName } = req.body;
    
    // 验证角色是否存在
    const role = await Role.findOne({ name: roleName, status: 1 });
    if (!role) {
      return res.status(400).json({
        success: false,
        message: '角色不存在或已禁用'
      });
    }
    
    const user = await User.findByIdAndUpdate(
      req.params.userId,
      { role: roleName },
      { new: true }
    ).select('-password');
    
    if (!user) {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      });
    }
    
    res.json({
      success: true,
      message: '角色分配成功',
      data: user
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '分配角色失败',
      error: error.message
    });
  }
});

// 初始化系统权限和角色
router.post('/init', auth, adminAuth, async (req, res) => {
  try {
    // 创建基础权限
    const basePermissions = [
      // 用户管理
      { name: 'user.create', displayName: '创建用户', module: '用户管理', action: 'create', resource: 'user' },
      { name: 'user.read', displayName: '查看用户', module: '用户管理', action: 'read', resource: 'user' },
      { name: 'user.update', displayName: '编辑用户', module: '用户管理', action: 'update', resource: 'user' },
      { name: 'user.delete', displayName: '删除用户', module: '用户管理', action: 'delete', resource: 'user' },
      
      // 商品管理
      { name: 'product.create', displayName: '创建商品', module: '商品管理', action: 'create', resource: 'product' },
      { name: 'product.read', displayName: '查看商品', module: '商品管理', action: 'read', resource: 'product' },
      { name: 'product.update', displayName: '编辑商品', module: '商品管理', action: 'update', resource: 'product' },
      { name: 'product.delete', displayName: '删除商品', module: '商品管理', action: 'delete', resource: 'product' },
      
      // 订单管理
      { name: 'order.read', displayName: '查看订单', module: '订单管理', action: 'read', resource: 'order' },
      { name: 'order.update', displayName: '处理订单', module: '订单管理', action: 'update', resource: 'order' },
      { name: 'order.delete', displayName: '删除订单', module: '订单管理', action: 'delete', resource: 'order' },
      
      // 广告管理
      { name: 'ad.create', displayName: '创建广告', module: '广告管理', action: 'create', resource: 'ad' },
      { name: 'ad.read', displayName: '查看广告', module: '广告管理', action: 'read', resource: 'ad' },
      { name: 'ad.update', displayName: '编辑广告', module: '广告管理', action: 'update', resource: 'ad' },
      { name: 'ad.delete', displayName: '删除广告', module: '广告管理', action: 'delete', resource: 'ad' },
      
      // 积分管理
      { name: 'points.read', displayName: '查看积分', module: '积分管理', action: 'read', resource: 'points' },
      { name: 'points.update', displayName: '调整积分', module: '积分管理', action: 'update', resource: 'points' },
      
      // 数据分析
      { name: 'analytics.read', displayName: '查看数据', module: '数据分析', action: 'read', resource: 'analytics' },
      
      // 权限管理
      { name: 'permission.manage', displayName: '权限管理', module: '系统管理', action: 'manage', resource: 'permission' },
      { name: 'role.manage', displayName: '角色管理', module: '系统管理', action: 'manage', resource: 'role' }
    ];
    
    // 批量创建权限（忽略重复）
    for (const permData of basePermissions) {
      await Permission.findOneAndUpdate(
        { name: permData.name },
        permData,
        { upsert: true, new: true }
      );
    }
    
    // 创建系统角色
    const systemRoles = [
      {
        name: 'admin',
        displayName: '超级管理员',
        description: '拥有所有权限的超级管理员',
        permissions: basePermissions.map(p => p.name),
        isSystem: true
      },
      {
        name: 'manager',
        displayName: '运营管理员',
        description: '负责日常运营管理',
        permissions: [
          'user.read', 'user.update',
          'product.create', 'product.read', 'product.update',
          'order.read', 'order.update',
          'ad.create', 'ad.read', 'ad.update',
          'points.read', 'points.update',
          'analytics.read'
        ],
        isSystem: true
      },
      {
        name: 'operator',
        displayName: '客服专员',
        description: '负责客户服务和订单处理',
        permissions: [
          'user.read',
          'order.read', 'order.update',
          'points.read'
        ],
        isSystem: true
      }
    ];
    
    // 批量创建角色（忽略重复）
    for (const roleData of systemRoles) {
      await Role.findOneAndUpdate(
        { name: roleData.name },
        roleData,
        { upsert: true, new: true }
      );
    }
    
    res.json({
      success: true,
      message: '系统权限和角色初始化成功',
      data: {
        permissionsCount: basePermissions.length,
        rolesCount: systemRoles.length
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '初始化失败',
      error: error.message
    });
  }
});

module.exports = router;